package com.vimi8.chick.plugins.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.widget.Toast;

import com.eros.framework.constant.Constant;
import com.eros.framework.http.Api;
import com.eros.framework.manager.ManagerFactory;
import com.eros.framework.manager.impl.FileManager;
import com.eros.framework.manager.impl.ModalManager;
import com.eros.framework.manager.impl.ParseManager;
import com.eros.framework.manager.impl.PermissionManager;
import com.eros.framework.manager.impl.PersistentManager;
import com.eros.framework.model.UploadImageBean;
import com.eros.framework.utils.ImageUtil;
import com.luck.picture.lib.PictureSelectionModel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.vimi8.chick.plugins.activity.VideoRecordActivity;
import com.vimi8.chick.plugins.manager.HttpManager;
import com.vimi8.chick.plugins.model.PictureBean;
import com.vimi8.chick.plugins.model.UploadObjectBean;
import com.vimi8.chick.plugins.model.VideoBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PictureAdapter {
    private static PictureAdapter mInstance = new PictureAdapter();

    private PictureAdapter() {
    }

    public static PictureAdapter getInstance() {
        return mInstance;
    }

    public void pickPhoto(final Context context, final PictureBean bean, final int requestCode) {
        PermissionManager permissionManager = ManagerFactory.getManagerService(PermissionManager.class);
        if (!permissionManager.hasPermissions(
            context,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )) {
            permissionManager.requestPermissions(context, new PermissionManager.PermissionListener() {
                    @Override
                    public void onPermissionsGranted(List<String> perms) {
                        pickPhotoWhenHasPermission(context, bean, requestCode);
                    }

                    @Override
                    public void onPermissionsDenied(List<String> perms) {
                        ModalManager.BmToast.toast(context, "读取sd卡存储权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onPermissionRequestRejected() {
                        ModalManager.BmToast.toast(context, "读取sd卡存储权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
                    }
                },
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            );
        } else {
            pickPhotoWhenHasPermission(context, bean, requestCode);
        }
    }

    private void pickPhotoWhenHasPermission(final Context context, PictureBean bean, int requestCode) {
        if (!checkPermission(context)) return;

        PictureSelector pictureSelector = PictureSelector.create((Activity) context);
        PictureSelectionModel pictureSelectionModel = pictureSelector
            .openGallery(PictureMimeType.ofImage())
            .selectionMode(PictureConfig.MULTIPLE)
            .maxSelectNum(bean.maxCount)
            .enableCrop(bean.allowCrop)
            .compress(true);
        if (bean.allowCrop && bean.ratioX != 0 && bean.ratioY != 0) {
            pictureSelectionModel.withAspectRatio(bean.ratioX, bean.ratioY);
        }
        if (bean.cropWidth != 0 && bean.cropHeight != 0) {
            pictureSelectionModel.cropWH(bean.cropWidth, bean.cropHeight);
        }
        pictureSelectionModel.forResult(requestCode);

        PersistentManager persistentManager = ManagerFactory.getManagerService(PersistentManager.class);
        persistentManager.setCacheData(Constant.ImageConstants.UPLOAD_IMAGE_BEAN, bean);
    }

    public void pickAvatar(final Context context, final PictureBean bean, final int requestCode) {
        // 动态获取权限
        PermissionManager permissionManager = ManagerFactory.getManagerService(PermissionManager.class);
        if (!permissionManager.hasPermissions(
            context,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )) {
            permissionManager.requestPermissions(context, new PermissionManager.PermissionListener() {
                    @Override
                    public void onPermissionsGranted(List<String> perms) {
                        pickAvatarWhenHasPermission(context, bean, requestCode);
                    }

                    @Override
                    public void onPermissionsDenied(List<String> perms) {
                        ModalManager.BmToast.toast(context, "读取sd卡存储权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onPermissionRequestRejected() {
                        ModalManager.BmToast.toast(context, "读取sd卡存储权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
                    }
                },
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            );
        } else {
            pickAvatarWhenHasPermission(context, bean, requestCode);
        }
    }

    private void pickAvatarWhenHasPermission(final Context context, PictureBean bean, int requestCode) {
        PictureSelector pictureSelector = PictureSelector.create((Activity) context);
        PictureSelectionModel pictureSelectionModel = pictureSelector
            .openGallery(PictureMimeType.ofImage())
            .selectionMode(PictureConfig.SINGLE)
            .maxSelectNum(bean.maxCount)
            .enableCrop(bean.allowCrop)
            .compress(true);
        if (bean.allowCrop && bean.ratioX != 0 && bean.ratioY != 0) {
            pictureSelectionModel.withAspectRatio(bean.ratioX, bean.ratioY);
        }
        if (bean.cropWidth != 0 && bean.cropHeight != 0) {
            pictureSelectionModel.cropWH(bean.cropWidth, bean.cropHeight);
        }
        pictureSelectionModel.forResult(requestCode);

        PersistentManager persistentManager = ManagerFactory.getManagerService(PersistentManager.class);
        persistentManager.setCacheData(Constant.ImageConstants.UPLOAD_IMAGE_BEAN, bean);
    }

    public void openCamera(final Context context, final PictureBean bean, final int requestCode) {
        // 动态获取权限
        PermissionManager permissionManager = ManagerFactory.getManagerService(PermissionManager.class);
        if (!permissionManager.hasPermissions(
            context,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )) {
            permissionManager.requestPermissions(context, new PermissionManager.PermissionListener() {
                    @Override
                    public void onPermissionsGranted(List<String> perms) {
                        openCameraWhenHasPermission(context, bean, requestCode);
                    }

                    @Override
                    public void onPermissionsDenied(List<String> perms) {
                        ModalManager.BmToast.toast(context, "摄像权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onPermissionRequestRejected() {
                        ModalManager.BmToast.toast(context, "摄像权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
                    }
                },
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            );
        } else {
            openCameraWhenHasPermission(context, bean, requestCode);
        }
    }

    private void openCameraWhenHasPermission(final Context context, PictureBean bean, int requestCode) {
        PictureSelector pictureSelector = PictureSelector.create((Activity) context);
        PictureSelectionModel pictureSelectionModel = pictureSelector
            .openCamera(PictureMimeType.ofImage())
            .selectionMode(PictureConfig.SINGLE)
            .maxSelectNum(bean.maxCount)
            .enableCrop(bean.allowCrop)
            .compress(true);
        if (bean.allowCrop && bean.ratioX != 0 && bean.ratioY != 0) {
            pictureSelectionModel.withAspectRatio(bean.ratioX, bean.ratioY);
        }
        if (bean.cropWidth != 0 && bean.cropHeight != 0) {
            pictureSelectionModel.cropWH(bean.cropWidth, bean.cropHeight);
        }
        pictureSelectionModel.forResult(requestCode);

        PersistentManager persistentManager = ManagerFactory.getManagerService(PersistentManager.class);
        persistentManager.setCacheData(Constant.ImageConstants.UPLOAD_IMAGE_BEAN, bean);
    }

    public void openVideo(final Context context, final VideoBean bean, final int requestCode) {
        // 动态获取权限
        PermissionManager permissionManager = ManagerFactory.getManagerService(PermissionManager.class);
        if (!permissionManager.hasPermissions(
            context,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )) {
            permissionManager.requestPermissions(context, new PermissionManager.PermissionListener() {
                    @Override
                    public void onPermissionsGranted(List<String> perms) {
                        openVideoWhenHasPermission(context, bean, requestCode);
                    }

                    @Override
                    public void onPermissionsDenied(List<String> perms) {
                        ModalManager.BmToast.toast(context, "摄像权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onPermissionRequestRejected() {
                        ModalManager.BmToast.toast(context, "摄像权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
                    }
                },
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            );
        } else {
            openVideoWhenHasPermission(context, bean, requestCode);
        }
    }

    private void openVideoWhenHasPermission(final Context context, VideoBean bean, int requestCode) {
        // 自定义视频录制功能
        // Intent intent = new Intent(context, VideoRecordActivity.class);
        // intent.putExtra("videoSecond", bean.videoSecond);
        Intent intent = new Intent(context, VideoRecordActivity.class);
        intent.putExtra("second", bean.second);
        intent.putExtra("type", bean.type);
        intent.putExtra("tip", bean.tip);
        intent.putExtra("quality", bean.quality);
        ((Activity) context).startActivityForResult(intent, requestCode);

        PersistentManager persistentManager = ManagerFactory.getManagerService(PersistentManager.class);
        persistentManager.setCacheData(Constant.ImageConstants.UPLOAD_IMAGE_BEAN, bean);
    }

    public void UpMultipleImageData(Context context, List<String> items, UploadImageBean bean) {
        ModalManager.BmLoading.showLoading(context, null, false);
        ArrayList imagesFileUrl = new ArrayList();
        if (items != null && items.size() > 0) {
            for (String item : items) {
                Bitmap bitmap = ImageUtil.getBitmap(item, context);
                String path = new File(FileManager.getTempFilePath(context), String.valueOf
                    (SystemClock.currentThreadTimeMillis())).getAbsolutePath();
                String imageFileUrl = ImageUtil.zoomImage(context, bitmap, bean == null ? 0 :
                    (int) bean.imageWidth, Constant
                    .ImageConstants.BIGGESTWIDTH, path);
                imagesFileUrl.add(imageFileUrl);
                bitmap.recycle();

            }
        }
        HashMap<String, String> uploadParams = null;
        HashMap<String, String> heads = null;
        if (bean != null) {
            String params = bean.params;
            ParseManager parseManager = ManagerFactory.getManagerService(ParseManager.class);
            uploadParams = parseManager.parseObject(params, HashMap.class);
            heads = parseManager.parseObject(bean.header, HashMap.class);
        }
        HttpManager httpManager = ManagerFactory.getManagerService(HttpManager.class);
        String url = TextUtils.isEmpty(bean.url) ? Api.UPLOAD_URL : bean.url;
        httpManager.upload(url, imagesFileUrl, uploadParams, heads);
    }

    public void uploadObject(Context context, List<String> items, UploadObjectBean bean) {
        ModalManager.BmLoading.showLoading(context, null, false);
        ArrayList fileUrls = new ArrayList();
        if (items != null && items.size() > 0) {
            for (String item : items) {
                String fileUrl = new File(item).getAbsolutePath();
                fileUrls.add(fileUrl);
            }
        }
        HashMap<String, String> uploadParams = null;
        HashMap<String, String> heads = null;
        if (bean != null) {
            String params = bean.params;
            ParseManager parseManager = ManagerFactory.getManagerService(ParseManager.class);
            uploadParams = parseManager.parseObject(params, HashMap.class);
            heads = parseManager.parseObject(bean.header, HashMap.class);
        }
        HttpManager httpManager = ManagerFactory.getManagerService(HttpManager.class);
        String url = TextUtils.isEmpty(bean.url) ? Api.UPLOAD_URL : bean.url;
        httpManager.upload(url, fileUrls, uploadParams, heads);
    }

    public void videoPreview(Context context, UploadImageBean bean) {
        PictureSelector.create((Activity) context).externalPictureVideo(bean.url);
    }

    private boolean checkPermission(Context context) {
        PermissionManager permissionManager = ManagerFactory.getManagerService(PermissionManager.class);
        boolean hasPermission = permissionManager.hasPermissions(context, Manifest.permission.READ_EXTERNAL_STORAGE) &&
            permissionManager.hasPermissions(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!hasPermission) {
            ModalManager.BmToast.toast(context, "读取sd卡存储权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
        }
        return hasPermission;
    }

    private boolean checkVideoPermission(Context context) {
        PermissionManager permissionManager = ManagerFactory.getManagerService(PermissionManager.class);
        boolean hasPermission = permissionManager.hasPermissions(context, Manifest.permission.RECORD_AUDIO) &&
            permissionManager.hasPermissions(context, Manifest.permission.CAMERA);
        if (!hasPermission) {
            ModalManager.BmToast.toast(context, "摄像权限未授予，请到应用设置页面开启权限!", Toast.LENGTH_SHORT);
        }
        return hasPermission;
    }
}
